using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using UnityEngine;
using UnityEngine.SceneManagement;

public class BCWServer : MonoBehaviour
{
	public static BCWServer instance;

	public static string _version = "1:1.0.3";

	private string json = "{\n\"TypeGame\":[\n{\n\"name\":\"Яростный Выхлопчег\",\n\"stars\":100500,\n\"place\":1,\n\"id\":\"26352269\"\n},\n{\n\"name\":\"Casy\",\n\"stars\":500,\n\"place\":2,\n\"id\":\"26352269\"\n},\n{\n\"name\":\"Безумный Стремитель\",\n\"stars\":100,\n\"place\":3,\n\"id\":\"26352269\"\n},\n{\n\"name\":\"Могильный Могильщик\",\n\"starts\":90,\n\"place\":4,\n\"id\":\"26352269\"\n},\n{\n\"name\":\"Djon\",\n\"stars\":60,\n\"place\":5,\n\"id\":\"26352269\"\n},\n{\n\"name\":\"Kazino\",\n\"stars\":10,\n\"place\":6,\n\"id\":\"26352269\"\n}\n]\n}\n";

	public string secret = string.Empty;

	public List<LeaderInfo> listCur = new List<LeaderInfo>();

	public static string idPlayer;

	private IEnumerator createPlayer;

	private static HMAC _hmac;

	private void Awake()
	{
		BCWDebug.Log("+++++++++++++++++++++++ Version For Server +" + _version.ToString());
		UnityEngine.Object.DontDestroyOnLoad(base.gameObject);
		instance = this;
		_hmac = new HMACSHA1(Encoding.UTF8.GetBytes(secret));
		idPlayer = BCWStorage.Get<string>(settings.keyIdPlayer);
		if (!TryParseIdPlayer(idPlayer) && createPlayer == null)
		{
			createPlayer = CreatIDPlayer();
			StartCoroutine(createPlayer);
		}
		StartCoroutine(SendPVPInfo());
	}

	public static void Init()
	{
		if (instance == null)
		{
			GameObject gameObject = UnityEngine.Object.Instantiate(new GameObject());
			gameObject.AddComponent<BCWServer>();
			instance = gameObject.GetComponent<BCWServer>();
			gameObject.name = "BCWServer";
		}
	}

	private void Start()
	{
		StartCoroutine(SendInfoLastOpening());
	}

	private void OnApplicationPause(bool pause)
	{
		if (!SceneManager.GetActiveScene().name.Equals("FirstLoading"))
		{
			StartCoroutine(SendInfoLastOpening(pause));
		}
	}

	private int GetGameModeNumber()
	{
		if (GameController.instance != null)
		{
			if (settings.offlineMode)
			{
				return 7;
			}
			switch (GameController.instance.curTypeGame)
			{
			case TypeGame.normal:
				return 3;
			case TypeGame.TDM:
				return 2;
			case TypeGame.race:
				return 4;
			case TypeGame.tanks:
				return 5;
			case TypeGame.Zombe:
				return 6;
			case TypeGame.CopsAndRobbers:
				return 8;
			case TypeGame.SkyBlock:
				return 9;
			case TypeGame.RocketLeague:
				return 10;
			case TypeGame.Pixelmon:
				return 11;
			case TypeGame.WalkingRobots:
				return 12;
			case TypeGame.TitanfallV2:
				return 13;
			default:
				return 1;
			}
		}
		return 1;
	}

	public static int GetIdModeByTypeGame(TypeGame typeGame)
	{
		switch (typeGame)
		{
		case TypeGame.Offline:
			return 0;
		case TypeGame.Lobby:
			return 1;
		case TypeGame.TDM:
			return 2;
		case TypeGame.OnlineSandbox:
			return 3;
		case TypeGame.race:
			return 4;
		case TypeGame.tanks:
			return 5;
		case TypeGame.Zombe:
			return 6;
		case TypeGame.normal:
			return 7;
		case TypeGame.CopsAndRobbers:
			return 8;
		case TypeGame.SkyBlock:
			return 9;
		case TypeGame.RocketLeague:
			return 10;
		case TypeGame.Pixelmon:
			return 11;
		case TypeGame.WalkingRobots:
			return 12;
		case TypeGame.TitanfallV2:
			return 13;
		default:
			return -1;
		}
	}

	public static TypeGame GetTypeGameByIdMode(int number)
	{
		switch (number)
		{
		case 0:
			return TypeGame.Offline;
		case 1:
			return TypeGame.Lobby;
		case 2:
			return TypeGame.TDM;
		case 3:
			return TypeGame.OnlineSandbox;
		case 4:
			return TypeGame.race;
		case 5:
			return TypeGame.tanks;
		case 6:
			return TypeGame.Zombe;
		case 7:
			return TypeGame.normal;
		case 8:
			return TypeGame.CopsAndRobbers;
		case 9:
			return TypeGame.SkyBlock;
		case 10:
			return TypeGame.RocketLeague;
		case 11:
			return TypeGame.Pixelmon;
		case 12:
			return TypeGame.WalkingRobots;
		case 13:
			return TypeGame.TitanfallV2;
		default:
			return TypeGame.Unknown;
		}
	}

	public static int ComparePhotonVersion(string first, string second)
	{
		if (string.IsNullOrEmpty(first) && string.IsNullOrEmpty(second))
		{
			return -1;
		}
		if (string.IsNullOrEmpty(first))
		{
			return -1;
		}
		if (string.IsNullOrEmpty(second))
		{
			return -1;
		}
		string text = first.ToCharArray().Aggregate(string.Empty, (string str, char ch) => (!char.IsDigit(ch)) ? str : (str + ch));
		int result;
		bool flag = int.TryParse(text, out result);
		string text2 = second.ToCharArray().Aggregate(string.Empty, (string str, char ch) => (!char.IsDigit(ch)) ? str : (str + ch));
		int result2;
		if (!(flag & int.TryParse(text2, out result2)))
		{
			BCWDebug.LogError("LOG: Fail to parse game version. Consider your version is newer!");
			return -1;
		}
		int num = Mathf.Abs(text.Length - text2.Length);
		int num2 = 1;
		for (int i = 0; i < num; i++)
		{
			num2 *= 10;
		}
		if (text.Length < text2.Length)
		{
			result *= num2;
		}
		else if (text2.Length < text.Length)
		{
			result2 *= num2;
		}
		return result.CompareTo(result2);
	}

	public void SendInfoPVP()
	{
		StartCoroutine(SendPVPInfo());
	}

	public IEnumerator SendPVPInfo()
	{
		while (true)
		{
			WWWForm form = new WWWForm();
			while (!TryParseIdPlayer(idPlayer))
			{
				yield return new WaitForSeconds(1f);
			}
			form.AddField("action", "update_player_online");
			form.AddField("id", idPlayer);
			if (PhotonNetwork.inRoom && PhotonNetwork.room != null)
			{
				form.AddField("roomName", PhotonNetwork.room.name);
			}
			form.AddField("app_version", _version);
			form.AddField("game_mode", GetGameModeNumber());
			form.AddField("map", SceneManager.GetActiveScene().name);
			WWW www = new WWW(headers: new Dictionary<string, string> { 
			{
				"Authorization",
				HashForPush(form.data)
			} }, url: URLs.bcwServer, postData: form.data);
			yield return www;
			string result = Sanitize(www);
			if (!string.IsNullOrEmpty(www.error))
			{
				BCWDebug.Log("Error download:  " + www.error);
			}
			else if (!string.IsNullOrEmpty(result) && result.Equals("fail"))
			{
				BCWDebug.Log("SendPVPInfo failed ");
			}
			else if (!string.IsNullOrEmpty(result))
			{
			}
			yield return new WaitForSeconds(15f);
		}
	}

	public void UpdatePlayerData()
	{
		StartCoroutine(UpadatePlayerDataIEnumerator());
	}

	private IEnumerator UpadatePlayerDataIEnumerator()
	{
		WWWForm form = new WWWForm();
		string playerName = settings.tekName;
		if (playerName.Length > 19)
		{
			playerName = playerName.Substring(0, 19);
		}
		string skinId = MarketController.Instance.GetEquipedSkinID();
		form.AddField("action", "update_player");
		form.AddField("id", idPlayer);
		form.AddField("name", playerName);
		form.AddField("skin", skinId);
		form.AddField("photonVersion", settings.verConnectPhoton);
		form.AddField("rank", BCWStorage.Get<int>(CupsManager.keyCurrentLeague).ToString());
		form.AddField("app_version", _version);
		WWW www = new WWW(headers: new Dictionary<string, string> { 
		{
			"Authorization",
			HashForPush(form.data)
		} }, url: URLs.bcwServer, postData: form.data);
		if (www == null)
		{
			BCWDebug.Log("UpadateNickAndSkin Error www download");
			yield break;
		}
		yield return www;
		string result = Sanitize(www);
		if (!string.IsNullOrEmpty(www.error))
		{
			BCWDebug.Log("UpadateNickAndSkin Error download:  " + www.error);
		}
		else if (!string.IsNullOrEmpty(result) && result.Equals("fail"))
		{
			BCWDebug.Log("UpadateNickAndSkin failed ");
		}
		else if (string.IsNullOrEmpty(result))
		{
			BCWDebug.Log("UpadateNickAndSkin result is empty");
		}
		else
		{
			BCWDebug.Log("UpadateNickAndSkin result " + result);
		}
	}

	public IEnumerator SendInfoLastOpening(bool immediatelySend = true)
	{
		if (BCWDebug.isDebugBuild)
		{
			BCWDebug.Log("SendInfoLastOpening");
		}
		if (!immediatelySend)
		{
			if (BCWDebug.isDebugBuild)
			{
				BCWDebug.Log("ShowAfterWait");
			}
			yield return new WaitForSeconds(5f);
		}
		BCWDebug.Log("deviceID" + SystemInfo.deviceUniqueIdentifier);
		WWWForm form = new WWWForm();
		string numberBuild = BuildNumberForInapps.BuildNumber.Replace(".", string.Empty);
		int number = 0;
		if (!int.TryParse(numberBuild, out number))
		{
			numberBuild = "0";
		}
		if (numberBuild.Length == 2)
		{
			numberBuild += "0";
		}
		while (!TryParseIdPlayer(idPlayer))
		{
			yield return new WaitForSeconds(1f);
		}
		int level = Load.LoadInt(settings.keyCurLevel) + 1;
		int paying = (Load.LoadBool(settings.keyPayment) ? 1 : 0);
		string playerName = BCWStorage.Get<string>(settings.keyCryptoName);
		if (playerName.Length > 19)
		{
			playerName = playerName.Substring(0, 19);
		}
		string skinId = string.Empty;
		if (PlayerPrefs.HasKey("skin"))
		{
			skinId = PlayerPrefs.GetString("skin");
		}
		form.AddField("action", "update_player");
		form.AddField("name", playerName);
		form.AddField("id", idPlayer);
		form.AddField("app_version", _version);
		form.AddField("paying", paying);
		form.AddField("skin", skinId);
		form.AddField("photonVersion", settings.verConnectPhoton);
		form.AddField("rank", BCWStorage.Get<int>(CupsManager.keyCurrentLeague).ToString());
		form.AddField("device", SystemInfo.deviceUniqueIdentifier);
		form.AddField("version", numberBuild);
		WWW www = new WWW(headers: new Dictionary<string, string> { 
		{
			"Authorization",
			HashForPush(form.data)
		} }, url: URLs.bcwServer, postData: form.data);
		if (www == null)
		{
			BCWDebug.Log("Error www download");
			yield break;
		}
		yield return www;
		string result = Sanitize(www);
		if (!string.IsNullOrEmpty(www.error))
		{
			BCWDebug.Log("Error download:  " + www.error);
		}
		else if (!string.IsNullOrEmpty(result) && result.Equals("fail"))
		{
			BCWDebug.Log("SendInfoLastOpening failed ");
		}
		else if (string.IsNullOrEmpty(result))
		{
			BCWDebug.Log("SendInfoLastOpening result is empty");
		}
		else
		{
			BCWDebug.Log("SendInfoLastOpening result " + result);
		}
	}

	public IEnumerator CreatIDPlayer()
	{
		string result;
		while (true)
		{
			if (BCWDebug.isDebugBuild)
			{
				BCWDebug.Log("CreatIDPlayer");
			}
			string numberBuild = BuildNumberForInapps.BuildNumber.Replace(".", string.Empty);
			int number = 0;
			if (!int.TryParse(numberBuild, out number))
			{
				numberBuild = "0";
			}
			if (numberBuild.Length == 2)
			{
				numberBuild += "0";
			}
			WWWForm form = new WWWForm();
			form.AddField("action", "create_player");
			form.AddField("name", settings.tekName);
			form.AddField("app_version", _version);
			form.AddField("device", SystemInfo.deviceUniqueIdentifier);
			form.AddField("version", numberBuild);
			WWW www = new WWW(headers: new Dictionary<string, string> { 
			{
				"Authorization",
				HashForPush(form.data)
			} }, url: URLs.bcwServer, postData: form.data);
			if (www == null)
			{
				BCWDebug.Log("Error www download");
				yield return new WaitForSeconds(10f);
				continue;
			}
			yield return www;
			result = Sanitize(www);
			if (!string.IsNullOrEmpty(www.error))
			{
				BCWDebug.Log("Error download:  " + www.error);
				yield return new WaitForSeconds(10f);
				continue;
			}
			if (!string.IsNullOrEmpty(result) && result.Equals("fail"))
			{
				BCWDebug.Log("CreatePlayer failed ");
				yield return new WaitForSeconds(10f);
				continue;
			}
			if (string.IsNullOrEmpty(result))
			{
				BCWDebug.Log("CreatePlayerId result is empty");
				yield return new WaitForSeconds(10f);
				continue;
			}
			if (TryParseIdPlayer(result))
			{
				break;
			}
			yield return new WaitForSeconds(10f);
		}
		SetIdPlayer(result);
		createPlayer = null;
	}

	public static bool TryParseIdPlayer(string idPlayer)
	{
		long result;
		if (!long.TryParse(idPlayer, out result))
		{
			if (Application.isPlaying)
			{
				BCWDebug.Log("CreatePlayer parsing error in result " + idPlayer);
			}
			return false;
		}
		if (result < 1)
		{
			if (Application.isPlaying)
			{
				BCWDebug.Log("CreatePlayerBad id" + idPlayer);
			}
			return false;
		}
		return true;
	}

	private void SetIdPlayer(string val)
	{
		if (BCWDebug.isDebugBuild)
		{
			BCWDebug.Log("SetIdPlayer: " + val);
		}
		idPlayer = val;
		BCWStorage.Set(settings.keyIdPlayer, val, true);
		ProtectedPrefs.SaveString(settings.keyIdPlayer, val);
		settings.UpdateIdPlayer();
	}

	public IEnumerator SendPaying(float dollars, string transactionId)
	{
		BCWDebug.Log("SendPaying");
		while (!TryParseIdPlayer(idPlayer))
		{
			yield return new WaitForSeconds(1f);
		}
		int iDollars = Mathf.RoundToInt(dollars * 100f);
		int level = Load.LoadInt(settings.keyCurLevel) + 1;
		WWWForm form = new WWWForm();
		form.AddField("action", "add_purchase");
		form.AddField("app_version", _version);
		form.AddField("id", idPlayer);
		form.AddField("inapp", iDollars);
		form.AddField("transaction_id", transactionId);
		form.AddField("rank", BCWStorage.Get<int>(CupsManager.keyCurrentLeague));
		WWW www = new WWW(headers: new Dictionary<string, string> { 
		{
			"Authorization",
			HashForPush(form.data)
		} }, url: URLs.bcwServer, postData: form.data);
		yield return www;
		string result = Sanitize(www);
		if (!string.IsNullOrEmpty(www.error))
		{
			BCWDebug.Log("Error download:  " + www.error);
		}
		else if (!string.IsNullOrEmpty(result) && result.Equals("fail"))
		{
			BCWDebug.Log("SendPaying failed ");
		}
		else if (string.IsNullOrEmpty(result))
		{
			BCWDebug.Log("SendPaying result is empty");
		}
		else
		{
			BCWDebug.Log("SendPaying result  " + result);
		}
	}

	public static string HashForPush(byte[] responceData)
	{
		if (responceData == null)
		{
			BCWDebug.LogWarning("HashForPush: responceData is null");
			return string.Empty;
		}
		if (_hmac == null)
		{
			_hmac = new HMACSHA1(Encoding.UTF8.GetBytes("ZaEb7Et.Im_SeC"));
		}
		byte[] array = _hmac.ComputeHash(responceData);
		string text = BitConverter.ToString(array);
		return text.Replace("-", string.Empty).ToLower();
	}

	public static string Sanitize(WWW request)
	{
		if (request == null)
		{
			return string.Empty;
		}
		if (!request.isDone)
		{
			throw new InvalidOperationException("Request should be done.");
		}
		if (!string.IsNullOrEmpty(request.error))
		{
			return string.Empty;
		}
		UTF8Encoding uTF8Encoding = new UTF8Encoding(false);
		return uTF8Encoding.GetString(request.bytes, 0, request.bytes.Length).Trim();
	}

	public static int GetLocalUnixTime()
	{
		return (int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds;
	}
}
